package com.jing.yao.modules.dict.controller;


import com.jing.yao.bean.ResponseBean;
import com.jing.yao.cache.CacheHelper;
import com.jing.yao.cache.RedisKeyEnum;
import com.jing.yao.component.controller.YaoBaseController;
import com.jing.yao.component.service.YaoBaseService;
import com.jing.yao.modules.dict.controller.dto.DictDTO;
import com.jing.yao.modules.dict.controller.param.DictParam;
import com.jing.yao.modules.dict.dao.entity.DictEntity;
import com.jing.yao.modules.dict.item.dao.entity.DictItemEntity;
import com.jing.yao.modules.dict.item.service.DictItemService;
import com.jing.yao.modules.dict.service.DictService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据字典
 *
 * @author
 */
@RestController
@RequestMapping("/dict")
public class DictController extends YaoBaseController<DictParam, DictEntity, DictDTO> {


    @Autowired
    private DictService dictService;
    @Autowired
    private DictItemService dictItemService;

    @Autowired
    private CacheHelper cacheHelper;

    @Override
    public YaoBaseService<DictParam, DictEntity> getService() {
        return dictService;
    }

    @Override
    public DictEntity getEntity() {
        return new DictEntity();
    }

    @Override
    public DictDTO getDTO() {
        return new DictDTO();
    }

    /**
     * 刷新数据字典
     *
     * @return
     */
    @GetMapping("/fresh")
    public ResponseBean refresh() {
        List<DictEntity> list = dictService.findAll();
        for (DictEntity dictEntity : list) {
            Map<String, String> dictCodeMap = dictItemService.list(Wrappers.<DictItemEntity>lambdaQuery()
                    .eq(DictItemEntity::getDictCode, dictEntity.getDictCode()))
                    .stream()
                    .collect(Collectors.toMap(DictItemEntity::getItemName, DictItemEntity::getItemValue));

            String key = RedisKeyEnum.DICT_PREFIX.getKey() + dictEntity.getDictCode();
            cacheHelper.delete(key);
            cacheHelper.hashSet(key, dictCodeMap);
        }
        return successBean();
    }
}
